const axios = require('axios');
const cheerio = require('cheerio');
const Tool = require('./../util/tool.js');
const log = require('./../util/log.js');


function parse(inputUrl, req, res, conf) {
    const options = {
        inputUrl: inputUrl,
        userAgent: Tool.randomEle(conf.phoneUA),
    }
    axios.get(inputUrl, {
        headers: {
            'User-Agent': options.userAgent,
        }
    }).then((response) => {
        let json = parseJson(response.data);
        //log.log("json", json)
        Object.assign(options, { json: json });
        getVideoInfo(options, req, res, conf);
    }).catch((error) => {
        let data = {
            status: 1,
            errMsg: "解析失败"
        };
        res.json(data);
        log.error(data);
        log.error('error 数据: ', error);
    }).finally(() => { });
}


function parseJson(html) {
    let $ = cheerio.load(html);
    let htmlData = $("#RENDER_DATA")?.html();
    if (!htmlData) {
        log.info("data source ::", html, htmlData);
        throw new Error("获取html-json失败", html);
    }
    let data = decodeURIComponent(htmlData);
    let json = JSON.parse(data);
    return json;
}

async function getVideoInfo(options, req, res, conf) {
    let result = await formatResult(options.json, conf)
    log.info('最终解析数据 : ', result);
    res.json({
        status: 0,
        data: result
    });
}

async function formatResult(data, conf) {

    let type, mainUrls;
    let videoRes = data.app.videoInfoRes.item_list?.[0];
    if(!videoRes){
        log.info("data source ::", data);
        throw new Error("读取数据丢失", data);
    }
    let author = videoRes.author;
    let video = videoRes.video;
    let info = {
        desc: videoRes.desc,
        photoId: videoRes.aweme_id,
        share_info: null
    }
    let user = {
        userName: author.nickname,
        userId: author.short_id,
        headUrl: (author.avatar_thumb.url_list || author.avatar_medium.url_list)?.[0]
    }

    let typeCode = videoRes.aweme_type;
    switch (typeCode) {
        case 2: // videoRes.aweme_type = 2 图集
            type = conf.resultType["atlas"];
            let photoUrls = videoRes.images.map(x => x.url_list);
            mainUrls = photoUrls.map(x => x?.[0]);
            Object.assign(info, {
                photoUrls: photoUrls,
                coverUrls: video.cover.url_list
            });
            break;
        case 4: // videoRes.aweme_type = 4 视频
            type = conf.resultType["video"];
            mainUrls = [await formatMainUrl(video.play_addr.url_list)];
            Object.assign(info, {
                videoUrls: mainUrls,
                coverUrls: video.cover.url_list
            });
            break;
        default:
            mainUrls = [];
            info = photo;
            break;
    }

    let result = {
        type: type,
        typeCode: typeCode,
        mainUrls: mainUrls,
        info: info,
        user: user
    }
    return result;
}


const playUrlRegx = new RegExp("(.*/play)wm(.*)");
async function formatMainUrl(url) {
    let result = playUrlRegx.exec(url);
    if (result) {
        result.shift();
        let turl = result.join("");
        return axios.head(turl, {
            maxRedirects: 0
        }).then((response) => {
            return turl;
        }).catch((error) => {
            return error.response.headers.location || turl;
        });
    } else {
        throw new Error("解析playwm url失败");
    }
}

module.exports = { parse };